package com.zyd.controller.wechat;


import com.zyd.exception.BusinessException;
import com.zyd.io.model.MealEntity;
import com.zyd.io.model.MenuEntity;
import com.zyd.io.model.UserEntity;
import com.zyd.io.model.VehicleEntity;
import com.zyd.io.vo.vehicle.VehicleTrackResVO;
import com.zyd.pojo.WeChatResult;
import com.zyd.service.wechat.WeChatService;
import com.zyd.util.WeChatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.RequestHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 微信小程序控制层
 */

@RestController
@RequestMapping("/wx")
public class WeChatController {


    @Autowired
    private WeChatService weChatService;

    /**
     * 发送验证码
     *
     * @param param mobile 手机号
     * @return
     */
    @PostMapping(value = "/smsCode")
    public WeChatResult smsCode(@RequestBody Map<String, String> param) {
        String mobile = param.get("mobile");
        if (StringUtils.isEmpty(mobile)) {
            return new WeChatResult<>(WeChatResult.ERROR, "手机号不能为空");
        }
        try {
            weChatService.smsCode(mobile);
            return new WeChatResult<>("成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new WeChatResult<>(WeChatResult.ERROR, e.getMessage());
        }
    }

    /**
     * 注册
     *
     * @param param mobile: 手机号, mcode: 验证码, openid: openid
     * @return
     */
    @PostMapping(value = "/register")
    public WeChatResult register(@RequestBody Map<String, String> param) {
        try {
            Map resultMap = weChatService.register(param);
            return new WeChatResult<>(resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            return new WeChatResult<>(WeChatResult.ERROR, e.getMessage());
        }

    }

    /**
     * 拿到微信的用户信息进行登录
     *
     * @param param
     * @return
     */
    @PostMapping(value = "/login")
    public WeChatResult login(@RequestBody Map<String, String> param) {
        try {
            HashMap<String, Object> result = new HashMap<>();
            String openId = weChatService.getOpenIdByWeChat(param);
            if (openId == null) {
                return new WeChatResult<>(WeChatResult.ERROR, "服务器忙");
            }
            UserEntity user = weChatService.findUserByOpenId(openId);
            result.put("openid", openId);
            if (user == null) {
                return new WeChatResult<>(2, result);
            }
            result.put("userid", user.getId());
            result.put("userclass", user.getUserclass());
            result.put("mobile", user.getMobile());
            return new WeChatResult<>(result);


        } catch (Exception e) {
            e.printStackTrace();
            return new WeChatResult<>(WeChatResult.ERROR, e.getMessage());
        }
    }

    /**
     * 根据userid查询车辆
     *
     * @param param userid
     * @return
     */
    @PostMapping(value = "/findCar")
    public WeChatResult findCarByUserid(@RequestBody Map<String, String> param) {
        try {
            String userid = param.get("userid");
            if (StringUtils.isEmpty(userid)) {
                return new WeChatResult<>(WeChatResult.ERROR, "用户信息不能为空");
            }
            List<VehicleEntity> list = weChatService.findCarByUserid(userid);
            return new WeChatResult<>(list);
        } catch (Exception e) {
            e.printStackTrace();
            return new WeChatResult<>(WeChatResult.ERROR, "服务器忙");
        }
    }

    /**
     * 根据车辆tagcode查询轨迹
     *
     * @param param tagcode   startTime endTime
     * @return
     */
    @PostMapping(value = "/findCarTrack")
    public WeChatResult findCarTrackByVehicleId(@RequestBody Map<String, String> param) {
        try {
            String tagcode = param.get("tagcode");
            if (StringUtils.isEmpty(tagcode)) {
                return new WeChatResult<>(WeChatResult.ERROR, "车辆信息不能为空");
            }
            List<VehicleTrackResVO> list = weChatService.findCarTrackByExample(param);
            return new WeChatResult<>(list);
        } catch (Exception e) {
            e.printStackTrace();
            return new WeChatResult<>(WeChatResult.ERROR, "服务器忙");
        }
    }

    /**
     * 根据车辆tagcode查询锁定或者开锁车辆
     *
     * @param param tagcode
     *              state  0解锁操作 1为锁定操作
     * @return
     */
    @PostMapping(value = "/updateLock")
    public WeChatResult updateLock(@RequestBody Map<String, String> param) {
        try {
            String tagcode = param.get("tagcode");
            if (StringUtils.isEmpty(tagcode)) {
                return new WeChatResult<>(WeChatResult.ERROR, "车辆信息不能为空");
            }
            String state = param.get("state");
            if (StringUtils.isEmpty(state) || (!"1".equals(state) && !"0".equals(state))) {
                return new WeChatResult<>(WeChatResult.ERROR, "服务器忙,数据异常");
            }
            weChatService.updateLock(tagcode, state);
            return new WeChatResult<>("操作成功");
        } catch (BusinessException e) {
            return new WeChatResult<>(2, e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new WeChatResult<>(WeChatResult.ERROR, "服务器忙");
        }
    }

    /**
     * 根据userid查询查询车辆和其对应的保险信息
     *
     * @param param userid
     * @return
     */
    @PostMapping(value = "/findMealAll")
    public WeChatResult findMealAll(@RequestBody Map<String, String> param) {
        try {
            String userid = param.get("userid");
            if (StringUtils.isEmpty(userid)) {
                return new WeChatResult<>(WeChatResult.ERROR, "用户信息不能为空");
            }
            List maps = weChatService.findMealByuserid(userid);
            return new WeChatResult<>(maps);
        } catch (BusinessException e) {
            return new WeChatResult<>(2, e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new WeChatResult<>(WeChatResult.ERROR, "服务器忙");
        }
    }

    /**
     * 根据车俩id查询明细
     *
     * @param param
     * @return
     */
    @PostMapping(value = "/findVehicle")
    public WeChatResult findVehicle(@RequestBody Map<String, String> param) {
        try {
            String id = param.get("id");
            if (StringUtils.isEmpty(id)) {
                return new WeChatResult<>(WeChatResult.ERROR, "车辆id不能为空");
            }
            VehicleEntity vehicle = weChatService.findVehicle(id);
            return new WeChatResult<>(vehicle);
        } catch (BusinessException e) {
            return new WeChatResult<>(2, e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new WeChatResult<>(WeChatResult.ERROR, "服务器忙");
        }
    }


    /**
     * 查询查询车辆所在地区的套餐保险信息
     *
     * @param param newareaid
     * @return
     */
    @PostMapping(value = "/findSafeAll")
    public WeChatResult findSafeAll(@RequestBody Map<String, String> param) {
        try {
            String newareaid = param.get("newareaid");
            if (StringUtils.isEmpty(newareaid)) {
                return new WeChatResult<>(WeChatResult.ERROR, "车辆信息不能为空");
            }
            List maps = weChatService.findSafeByNewareaid(newareaid);
            return new WeChatResult<>(maps);
        } catch (BusinessException e) {
            return new WeChatResult<>(2, e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new WeChatResult<>(WeChatResult.ERROR, "服务器忙");
        }
    }


    /**
     * 车辆续保
     *
     * @param param
     * @return
     */
    @PostMapping(value = "/renewal")
    public WeChatResult renewal(@RequestBody Map<String, String> param) {
        try {
            Map map = weChatService.renewal(param);

            return new WeChatResult<>(map);
        } catch (BusinessException e) {
            return new WeChatResult<>(2, e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new WeChatResult<>(WeChatResult.ERROR, "服务器忙");
        }
    }

    /**
     * 支付成功
     *
     * @param param
     * @return
     */
    @PostMapping(value = "/payInfo")
    public WeChatResult payInfo(@RequestBody Map<String, String> param) {
        try {
            String orderId = param.get("orderId");
            if (StringUtils.isEmpty(orderId)) {
                return new WeChatResult<>(WeChatResult.ERROR, "订单错误");
            }
            weChatService.payInfo(orderId);

            return new WeChatResult<>("OK");
        } catch (BusinessException e) {
            return new WeChatResult<>(2, e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new WeChatResult<>(WeChatResult.ERROR, "服务器忙");
        }
    }

    /**
     * 查询所有区县以供选择
     * @return
     */
    @PostMapping(value = "/findCountry")
    public WeChatResult findCountry() {
        try {
            List countryList = weChatService.findCountry();
            return new WeChatResult<>(countryList);
        } catch (BusinessException e) {
            return new WeChatResult<>(2, e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new WeChatResult<>(WeChatResult.ERROR, "服务器忙");
        }
    }
    /**
     * 查询所有安装网点以供选择
     * @return
     */
    @PostMapping(value = "/findNetwork")
    public WeChatResult findNetwork() {
        try {
            List countryList = weChatService.findNetwork();
            return new WeChatResult<>(countryList);
        } catch (BusinessException e) {
            return new WeChatResult<>(2, e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new WeChatResult<>(WeChatResult.ERROR, "服务器忙");
        }
    }

    /**
     *  添加车辆通过其他方式支付
     * @param param
     * @return
     */
    @PostMapping(value = "/addVehicleOfOtherPay")
    public WeChatResult addVehicleOfOtherPay(@RequestBody VehicleEntity param) {
        try {
            weChatService.addVehicleToExamine(param,0);
            return new WeChatResult<>("OK");
        } catch (BusinessException e) {
            return new WeChatResult<>(2, e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new WeChatResult<>(WeChatResult.ERROR, "服务器忙");
        }
    }

    /**
     *  添加车辆通过 微信支付
     * @param param
     * @return
     */
    @PostMapping(value = "/addVehicleOfWeChatPay")
    public WeChatResult addVehicleOfWeChatPay(@RequestBody VehicleEntity param) {
        try {
            Map map = weChatService.addVehicleOfWeChatPay(param);
            return new WeChatResult<>(map);
        } catch (BusinessException e) {
            return new WeChatResult<>(2, e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new WeChatResult<>(WeChatResult.ERROR, "服务器忙");
        }
    }

    /**
     * 添加车辆通过 微信支付成功后
     * *
     * @param param
     * @return
     */
    @PostMapping(value = "/addVehiclePayInfo")
    public WeChatResult addVehiclePayInfo(@RequestBody Map<String, String> param) {
        try {
            String orderId = param.get("orderId");
            if (StringUtils.isEmpty(orderId)) {
                return new WeChatResult<>(WeChatResult.ERROR, "订单错误");
            }
            weChatService.addVehiclePayInfo(orderId);

            return new WeChatResult<>("OK");
        } catch (BusinessException e) {
            return new WeChatResult<>(2, e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new WeChatResult<>(WeChatResult.ERROR, "服务器忙");
        }
    }

    @PostMapping(value = "/findVehicleExamine")
    public WeChatResult findVehicleExamine(@RequestBody Map<String, String> param) {
        try {
            String userid = param.get("userid");
            if (StringUtils.isEmpty(userid)) {
                return new WeChatResult<>(WeChatResult.ERROR, "用户信息不能为空");
            }
            List<VehicleEntity> list = weChatService.findVehicleExamine(userid);
            return new WeChatResult<>(list);
        } catch (Exception e) {
            e.printStackTrace();
            return new WeChatResult<>(WeChatResult.ERROR, "服务器忙");
        }
    }
    /**
     * 接收微信支付结果通知
     * 没发测试 gg
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/notify")
    public String notify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String result = null;//返回给微信的处理结果
        String inputLine;
        String notityXml = "";
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        //微信给返回的东西
        Map map = WeChatUtils.xmlToMap(notityXml);
        // 解析各种数据
        String appid = (String) map.get("appid");//应用ID
        String attach = (String) map.get("attach");//商家数据包
        String bank_type = (String) map.get("bank_type");//付款银行
        String cash_fee = (String) map.get("cash_fee");//现金支付金额
        String fee_type = (String) map.get("fee_type");//货币种类
        String is_subscribe = (String) map.get("is_subscribe");//是否关注公众账号
        String mch_id = (String) map.get("mch_id");//商户号
        String nonce_str = (String) map.get("nonce_str");//随机字符串
        String openid = (String) map.get("openid");//用户标识
        String out_trade_no = (String) map.get("out_trade_no");// 获取商户订单号
        String result_code = (String) map.get("result_code");// 业务结果
        String return_code = (String) map.get("return_code");// SUCCESS/FAIL
        String sign = (String) map.get("sign");// 获取签名
        String time_end = (String) map.get("time_end");//支付完成时间
        String total_fee = (String) map.get("total_fee");// 获取订单金额
        String trade_type = (String) map.get("trade_type");//交易类型
        String transaction_id = (String) map.get("transaction_id");//微信支付订单号

        SortedMap<String, String> parameters = new TreeMap<String, String>();
        // 数据加密
        parameters.put("appid", appid);//应用ID
        parameters.put("attach", attach);//商家数据包
        parameters.put("bank_type", bank_type);//付款银行
        parameters.put("cash_fee", cash_fee);//现金支付金额
        parameters.put("fee_type", fee_type);//货币种类
        parameters.put("is_subscribe", is_subscribe);//是否关注公众账号
        parameters.put("mch_id", mch_id);//商户号
        parameters.put("nonce_str", nonce_str);//随机字符串
        parameters.put("openid", openid);//用户标识
        parameters.put("out_trade_no", out_trade_no);// 商户订单号
        parameters.put("result_code", result_code);// 业务结果
        parameters.put("return_code", return_code);// SUCCESS/FAIL
        parameters.put("time_end", time_end);// 支付完成时间
        parameters.put("total_fee", total_fee);// 获取订单金额
        parameters.put("trade_type", trade_type);//交易类型
        parameters.put("transaction_id", trade_type);//微信支付订单号
        //加密前验证notify支付订单网关---https://gw.tenpay.com/gateway/simpleverifynotifyid.xml
//        RequestHandler reqHandler = new RequestHandler(request, response);
//        reqHandler.init(appid, appsecret, partnerkey);
//        //MD5加密
//        String endsign = reqHandler.createSign(parameters);


        System.out.println("**************************************************************************************************");
        System.out.println(appid + "-------------------应用ID");
        System.out.println(attach + "-------------------商家数据包");
        System.out.println(bank_type + "-------------------付款银行");
        System.out.println(cash_fee + "-------------------现金支付金额");
        System.out.println(fee_type + "-------------------货币种类");
        System.out.println(is_subscribe + "-------------------是否关注公众账号");
        System.out.println(mch_id + "-------------------商户号");
        System.out.println(nonce_str + "-------------------随机字符串");
        System.out.println(openid + "-------------------用户标识");
        System.out.println(out_trade_no + "-------------------获取商户订单号");
        System.out.println(result_code + "-------------------业务结果");
        System.out.println(return_code + "------------------- SUCCESS/FAIL");
        System.out.println(sign + "-------------------获取签名-微信回调的签名");
        System.out.println(time_end + "-------------------支付完成时间");
        System.out.println(total_fee + "-------------------获取订单金额");
        System.out.println(trade_type + "-------------------交易类型");
        System.out.println(transaction_id + "-------------------微信支付订单号");
        System.out.println("**************************************************************************************************");

        System.out.println("回调成功");
        System.out.println("----返回给微信的xml：" + result);
        return result;
    }


}
